<template>
  <div>
    <!-- 添加食谱 -->
    <div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        status-icon
        hide-required-asterisk
      >
        <el-form-item label="食谱名称" prop="recipeName">
          <el-input v-model="ruleForm.recipeName" />
        </el-form-item>
        <el-form-item label="推荐指数" prop="stars">
          <el-select
            v-model="ruleForm.stars"
            placeholder="推荐指数"
            class="handle-select mr10"
          >
            <!-- <el-option key="4" label="全部类型" value=""></el-option> -->
            <el-option key="0" label="暂无" value="0"></el-option>
            <el-option key="1颗星" label="1颗星" :value="1"></el-option>
            <el-option key="2颗星" label="2颗星" :value="2"></el-option>
            <el-option key="3颗星" label="3颗星" :value="3"></el-option>
            <el-option key="4颗星" label="4颗星" :value="4"></el-option>
            <el-option key="5颗星" label="5颗星" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择食谱封面图" height="40">
          <el-upload
            action="#"
            :multiple="false"
            accept=".jpg,.jpeg,.png"
            :show-file-list="true"
            list-type="picture-card"
            @change="handelFileChange"
            :auto-upload="false"
          >
            <el-image class="avatar" v-if="imageUrl" :src="imageUrl" />
            <el-icon v-else>
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">jpg/png格式图片且图片大小不能超过500kb</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="ruleForm.type">
            <el-radio :label="0">普通</el-radio>
            <el-radio :label="1">推荐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="就餐类别" prop="category">
          <el-radio-group v-model="ruleForm.category">
            <el-radio :label="0">早餐</el-radio>
            <el-radio :label="1">午餐</el-radio>
            <el-radio :label="2">晚餐</el-radio>
            <el-radio :label="3">加餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="添加食物" prop="foods">
          <el-select-v2
            v-model="searchRecipeName"
            style="width: 240px"
            multiple
            filterable
            remote
            :remote-method="remoteMethod"
            clearable
            :options="options"
            @change="hanldeInfo"
            placeholder="请输入食物"
            :loading="loading"
          />
        </el-form-item>
        <el-table :data="ruleForm.foods" border class="table" header-cell-class-name="table-header" ref="ruleForm.foods">
          <el-table-column prop="foodName" label="食物名称" min-width="33%"></el-table-column>
          <el-table-column prop="foodWeight" label="食物重量(g)" min-width="33%">
            <template #default="scope">
              <span>
                <!-- <el-input v-model="scope.row.foodWeight" :step="1" :step-strictly="true" placeholder="请输入重量" size="mini" min="1"/> -->
                <el-input-number v-model="scope.row.foodWeight" :step="1" :step-strictly="true" placeholder="请输入重量" size="mini" min="0" maxlength="300px"  style="width: auto;"/>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="foodCount" label="食物数量" min-width="33%">
            <template #default="scope">
              <span>
                <!-- <el-input-number v-model="scope.row.foodWeight" :step="1" :step-strictly="true" placeholder="请输入重量" size="mini" min="1"/> -->
                <el-input-number
                  v-model="scope.row.foodCount"
                  maxlength="300"
                  placeholder="请输入数量"
                  size="mini"
                  :step="1"
                  :step-strictly="true"
                  min="1"
                  style="width: auto"
                />
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="制作指南">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="valueHtml"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button type="primary" @click="submitFormAdd(ruleFormRef)"
        >提交</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      <el-button @click="handlePage">取消</el-button>
    </span>
  </div>
</template>

<script>
import { ref, reactive, onBeforeMount, onMounted } from 'vue'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  components: { Editor, Toolbar },
  setup() {
    const router = useRouter()

    // const isLoading  = true
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    const handleImage = () => {}
    // 内容 HTML
    const valueHtml = ref('')
    const toolbarConfig = {}
    const editorConfig = { MENU_CONF: {} }
    editorConfig.MENU_CONF['uploadImage'] = {
      // 自定义上传
      async customUpload(file, insertFn) {
        // TS 语法
        // this.isLoading = false
        let formdata = new FormData()
        formdata.append('files', file)
        const url = ref('')
        request
          .request({
            url: '/knowledge/imageAdd',
            method: 'post',
            data: formdata,
            headers: { 'Content-Type': 'multipart/form-data' },
          })
          .then((res) => {
            if (res.data.code == 200) {
              ElNotification({
                title: '图片上传成功',
                message: '图片上传成功',
              })
              url.value = res.data.data.payload[0]
              insertFn(url.value)
              // const paths = res.data.data.payload
            } else if (res.data.data.code == 0) {
              ElNotification({
                title: '图片上传失败',
                message: '图片过大，请重新选择图片',
              })
            }
          })
      },
      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {
        // TS 语法
        // onError(file, err, res) {               // JS 语法
        console.log(`${file.name} 上传出错`, err, res)
      },
    }
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const route = useRoute()
    const rules = reactive({
      recipeName: [
        {
          required: true,
          message: '请输入食谱名称',
          trigger: 'blur',
        },
      ],
      stars: [
        {
          required: true,
          message: '推荐指数必填',
          trigger: 'change',
        },
      ],
      directions: [
        {
          required: true,
          message: '请填写制作指南',
          trigger: 'blur',
        },
      ],
      avator: [
        {
          required: true,
          message: '食谱封面必填',
          trigger: 'change',
        },
      ],
      type: [
        {
          required: true,
          message: '请选择类型',
          trigger: 'change',
        },
      ],
      category: [
        {
          required: true,
          message: '请选择食谱类别',
          trigger: 'change',
        },
      ],
      foods: [
        {
          required: true,
          message: '请添加食物',
          trigger: 'blur',
        },
      ],
    })
    const searchRecipeName = ref([])
    const ruleFormRef = ref({})
    const imageUrl = ref('')
    const ruleForm = ref({
      recipeId: route.query.recipeId,
      recipeName: '',
      category: 0,
      type: 0,
      directions: '',
      avator: '',
      stars: '0',
      foods: [],
    })
    // 查询食谱组成
    const options = ref([])
    const recipeMake = async () => {
      await request
        .request({
          url: '/recipe/getRecipeById',
          params: { recipeId: route.query.recipeId },
          method: 'get',
        })
        .then((res) => {
          ruleForm.value.recipeName = res.data.data.recipeName
          ruleForm.value.category = res.data.data.category
          ruleForm.value.type = res.data.data.type
          ruleForm.value.directions = res.data.data.directions
          valueHtml.value = res.data.data.directions
          ruleForm.value.stars =
            res.data.data.stars == 0 ? '0' : res.data.data.stars
          ruleForm.value.avator = res.data.data.avator
          imageUrl.value = res.data.data.avator
          ruleForm.value.foods = res.data.data.foods.map((item) => {
            return {
              foodId: item.foodId,
              foodName: item.foodName,
              foodWeight: item.recipeDetail.foodWeight,
              foodCount: item.recipeDetail.foodCount,
            }
          })
          options.value = res.data.data.foods.map((item) => {
            return {
              value: item.foodId + ',' + item.foodName,
              label: item.foodName,
            }
          })
          for (let i in options.value) {
            searchRecipeName.value.push(options.value[i].value)
          }
        })
    }
    recipeMake()
    // 重置表单
    const resetForm = (formEl) => {
      recipeMake()
      ElNotification({
        title: '重置成功',
        message: '重置成功',
      })
    }
    // 获取文件数据
    const selectedFile = ref(null)
    const handelFileChange = (file) => {
      const isLt500k = file.raw.size / 1024 < 500
      if (!isLt500k) {
        ElNotification({
          title: '图片过大',
          message: '图片不能超过500k',
        })
        return
      }
      selectedFile.value = file.raw
      imageUrl.value = URL.createObjectURL(file.raw)
    }

    const formData = ref(null)

    const loading = ref(true)
    // 搜索食物信息
    const remoteMethod = (searchRecipeName) => {
      if (searchRecipeName != '') {
        request
          .request({
            url: '/food/getAllFoodByNameFR',
            method: 'get',
            params: {
              foodName: searchRecipeName,
            },
          })
          .then((res) => {
            if (res.data.code == 200) {
              options.value = res.data.data[1].map((item) => {
                // const [name, id] = item.split('_')
                const name = item.split('#')[0]
                const id = item.split('#')[1].split('_')[0]
                return {
                  value: id + ',' + name,
                  label: name,
                }
              })
              loading.value = false
            } else {
              ElNotification({
                title: '添加失败',
                message: '请联系管理员检查失败原因',
              })
            }
          })
          .catch((e) => {
            ElNotification({
              title: '添加失败',
              message: '请联系管理员检查失败原因' + e,
            })
          })
      }
    }

    const hanldeInfo = (val) => {
      let food = []
      // 筛选出已存在的食物添加到新数组
      food = ruleForm.value.foods.filter((item) => {
        let idList = val.map((v) => {
          const [id, name] = v.split(',')
          return id
        })
        return idList.includes(item.foodId)
      })

      // 如果该食物不存在则添加到新数组中
      for (let i = 0; i < val.length; i++) {
        const [id, name] = val[i].split(',')
        const Index = food.findIndex((item) => {
          return item.foodId === id
        })
        if (Index === -1) {
          food.push({
            foodId: id,
            foodName: name,
            foodWeight: 0,
            foodCount: 0,
          })
        }
        // 前两个数据的key值相同，打印出对应的下标 ，后面找不相同的key  输出-1
      }
      ruleForm.value.foods = []
      ruleForm.value.foods = [...food]
    }

    // 处理添加方法的参数数据
    const processFormData = () => {
      const formData = new FormData()
      formData.append('recipeId', ruleForm.value.recipeId)
      formData.append('recipeName', ruleForm.value.recipeName)
      formData.append('category', Number(ruleForm.value.category))
      formData.append('type', Number(ruleForm.value.type))
      formData.append('directions', valueHtml.value)
      // 处理上传图片
      if (selectedFile.value) {
        const fileName = selectedFile.value.name
        formData.append('avator', selectedFile.value, fileName)
      } else {
        formData.append('avator', '')
      }
      formData.append('stars', Number(ruleForm.value.stars))
      // 处理食物数据
      ruleForm.value.foods.forEach((item, index, arr) => {
        delete item['foodName']
      })
      if (ruleForm.value.foods.length !== 0) {
        formData.append('foods', JSON.stringify(ruleForm.value.foods))
      } else {
        formData.append('foods', '')
      }

      if (ruleForm.value.desc) {
        formData.append('desc', ruleForm.value.desc)
      }

      return formData
    }
    //更新食谱
    const submitFormAdd = async (formEl) => {
      if (valueHtml.value == '<p><br></p>') {
        ElNotification({
          title: '添加失败',
          message: '请添加制作指南',
        })
        return
      }
      if (!formEl) {
        ElNotification({
          title: '添加失败',
          message: '请完善食谱信息',
        })
        return
      }
      for (const item of ruleForm.value.foods) {
        if (item.foodWeight == 0) {
          ElNotification({
            title: '添加失败',
            message: '食物重量不能为0',
          })
          return
        }
      }
      formData.value = processFormData()
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          request
            .request({
              url: '/recipe/updateRecipe',
              method: 'post',
              data: formData.value,
              headers: { 'Content-Type': 'multipart/form-data' },
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '更新成功',
                  message: '成功更新食谱信息',
                })
                setTimeout(() => {
                  router.push('recipeTable')
                }, 1000)
              } else {
                ElNotification({
                  title: '更新失败',
                  message: '请联系管理员检查失败原因',
                })
              }
            })
            .catch((e) => {
              console.log(e)
              ElNotification({
                title: '更新失败',
                message: '请联系管理员检查失败原因' + e,
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }
    const handlePage = () => {
      router.push('recipeTable')
    }
    return {
      ruleForm,
      ruleFormRef,
      rules,
      resetForm,
      submitFormAdd,
      handelFileChange,
      remoteMethod,
      options,
      loading,
      searchRecipeName,
      hanldeInfo,
      imageUrl,
      selectedFile,
      formData,
      recipeMake,
      handlePage,
      editorRef,
      valueHtml,
      mode: 'default',
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleImage,
    }
  },
}
</script>

<style lang="scss" scoped>
.table {
  width: 81.5%;
  font-size: 14px;
  margin-left: 120px;
}

.mr10 {
  margin-right: 10px;
}
</style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}
.avatar-uploader .avatar{
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
</style>
